var mxIsElectron = window && window.process && window.process.type;
var mxIsElectron5 = mxIsElectron && parseInt(process.versions.electron) >= 5;
var hostName = window.location.hostname;
// Supported domains are *.draw.io that draw.io host, or the packaged version in Quip
var supportedDomain = (hostName.substring(hostName.length - 8, hostName.length) === '.draw.io') ||
    (hostName.substring(hostName.length - 17, hostName.length) === '.quipelements.com');

/**
 * URL Parameters and protocol description are here:
 *
 * https://desk.draw.io/support/solutions/articles/16000042546-what-url-parameters-are-supported
 *
 * Parameters for developers:
 *
 * - dev=1: For developers only
 * - test=1: For developers only
 * - export=URL for export: For developers only
 * - ignoremime=1: For developers only (see DriveClient.js). Use Cmd-S to override mime.
 * - createindex=1: For developers only (see etc/build/README)
 * - filesupport=0: For developers only (see Editor.js in core)
 * - savesidebar=1: For developers only (see Sidebar.js)
 * - pages=1: For developers only (see Pages.js)
 * - lic=email: For developers only (see LicenseServlet.java)
 * --
 * - networkshapes=1: For testing network shapes (temporary)
 */
var urlParams = (function()
{
    var result = new Object();
    var params = window.location.search.slice(1).split('&');

    for (var i = 0; i < params.length; i++)
    {
        idx = params[i].indexOf('=');

        if (idx > 0)
        {
            result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
        }
    }

    return result;
})();

// Forces CDN caches by passing URL parameters via URL hash
if (window.location.hash != null && window.location.hash.substring(0, 2) == '#P')
{
    try
    {
        urlParams = JSON.parse(decodeURIComponent(window.location.hash.substring(2)));

        if (urlParams.hash != null)
        {
            window.location.hash = urlParams.hash;
        }
    }
    catch (e)
    {
        // ignore
    }
}

// Redirects page if required
if (urlParams['dev'] != '1')
{
    (function()
    {
        var proto = window.location.protocol;

        if (!mxIsElectron)
        {
            var host = window.location.host;

            // Redirects apex and rt to www
            if (host === 'draw.io' || host === 'rt.draw.io')
            {
                host = 'www.draw.io';
            }

            var href = proto + '//' + host + window.location.href.substring(
                window.location.protocol.length +
                window.location.host.length + 2);

            // Redirects if href changes
            if (href != window.location.href)
            {
                window.location.href = href;
            }
        }
        else if (!mxIsElectron5)
        {
            // It's electron, but v3 or lower
            window.location.href = 'https://about.draw.io/updates-to-draw-io-desktop/';
        }
    })();
}

/**
 * Adds meta tags with application name (depends on offline URL parameter)
 */
(function()
{
    function addMeta(name, content, httpEquiv)
    {
        try
        {
            var s = document.createElement('meta');

            if (name != null)
            {
                s.setAttribute('name', name);
            }

            s.setAttribute('content', content);

            if (httpEquiv != null)
            {
                s.setAttribute('http-equiv', httpEquiv);
            }

            var t = document.getElementsByTagName('meta')[0];
            t.parentNode.insertBefore(s, t);
        }
        catch (e)
        {
            // ignore
        }
    };

    var name = 'draw.io';

    if (urlParams['offline'] === '1')
    {
        name += ' app';
    }

    addMeta('apple-mobile-web-app-title', name);
    addMeta('application-name', name);

    if (mxIsElectron5)
    {
        addMeta(null, 'default-src \'self\' \'unsafe-inline\'; connect-src \'self\' https://*.draw.io; img-src * data:; media-src *; font-src *', 'Content-Security-Policy');
    }
})();

/**
 * Synchronously adds scripts to the page.
 */
function mxscript(src, onLoad, id, dataAppKey, noWrite, type='text/javascript')
{
    if (onLoad != null || noWrite)
    {
        var s = document.createElement('script');
        s.setAttribute('type', type);
        s.setAttribute('src', src);
        var r = false;

        if (id != null)
        {
            s.setAttribute('id', id);
        }

        if (dataAppKey != null)
        {
            s.setAttribute('data-app-key', dataAppKey);
        }

        if (onLoad != null)
        {
            s.onload = s.onreadystatechange = function()
            {
                if (!r && (!this.readyState || this.readyState == 'complete'))
                {
                    r = true;
                    onLoad();
                }
            };
        }

        var t = document.getElementsByTagName('script')[0];
        t.parentNode.insertBefore(s, t);
    }
    else
    {
        document.write('<script src="' + src + '"' + ((id != null) ? ' id="' + id +'" ' : '') +
            ((dataAppKey != null) ? ' data-app-key="' + dataAppKey +'" ' : '') +
            ((type != null) ? ' type="' + type +'" ' : '')
            +'></script>');
    }
};

/**
 * Asynchronously adds scripts to the page.
 */
function mxinclude(src)
{
    var g = document.createElement('script'); g.type = 'text/javascript'; g.async = true; g.src = src;
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(g, s);
};

// Checks for local storage
var isLocalStorage = false;

try
{
    isLocalStorage = urlParams['local'] != '1' && typeof(localStorage) != 'undefined';
}
catch (e)
{
    // ignored
}

var t0 = new Date();

// Changes paths for local development environment
if (urlParams['dev'] == '1')
{
    window.mxOfflineMode = true;
    mxscript('js/PreConfig.js');
    mxscript('js/diagramly/Init.js');
    mxscript('js/mxgraph/Init.js');
    mxscript('js/mxClient.js');
    mxscript('js/diagramly/Devel.js');
    mxscript('js/PostConfig.js');
    mxscript('js/main.js',null,null,null,false,'module');
}
else
{
    mxscript('js/app.min.js');
    mxscript('js/main.min.js',null,null,null,false,'module');
}

// Electron
if (mxIsElectron)
{
    mxscript('js/PreConfig.js');
    mxscript('js/diagramly/DesktopLibrary.js');
    mxscript('js/diagramly/ElectronApp.js');
    mxscript('js/extensions.min.js');
    mxscript('js/stencils.min.js');
    mxscript('js/shapes.min.js');
    mxscript('js/PostConfig.js');
}

// Adds basic error handling
window.onerror = function()
{
    var status = document.getElementById('geStatus');

    if (status != null)
    {
        status.innerHTML = 'Page could not be loaded. Please try refreshing.';
    }
};
